package fun.tan90.device.sink.td.plugin.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.dialect.DbType;
import fun.tan90.device.sink.core.SinkFactory;
import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;

import java.util.function.BiConsumer;

@Slf4j
@Component
public class TdClientFactory extends SinkFactory {

    @Override
    public Class<?> init(ONode connectNode, BiConsumer<String, Object> biConsumer) {
        FlexGlobalConfig defaultConfig = FlexGlobalConfig.getDefaultConfig();
        defaultConfig.setPrintBanner(false);
        defaultConfig.setDbType(DbType.TDENGINE);

        MybatisFlexBootstrap mybatisFlexBootstrap = MybatisFlexBootstrap.getInstance();
        for (ONode node : connectNode.ary()) {
            String name = node.get("name").getString();
            ONode connect = node.get("connect");

            DruidDataSource druidDataSource = new DruidDataSource();
            // jdbc properties
            druidDataSource.setName(name);
            druidDataSource.setDriverClassName(connect.get("driverClassName").getString());
            druidDataSource.setUrl(connect.get("jdbcUrl").getString());
            druidDataSource.setUsername(connect.get("username").getString());
            druidDataSource.setPassword(connect.get("password").getString());
            // connection pool configurations
            druidDataSource.setInitialSize(10);
            druidDataSource.setMinIdle(10);
            druidDataSource.setMaxActive(10);
            druidDataSource.setMaxWait(30000);
            druidDataSource.setValidationQuery("SELECT SERVER_VERSION()");

            try {
                druidDataSource.init();
                clientInitSuccess(name);
            } catch (Exception e) {
                clientInitFailure(name, e);
            }

            mybatisFlexBootstrap.addDataSource(name, druidDataSource);
        }
        mybatisFlexBootstrap.start();

        //设置 SQL 审计收集器
        AuditManager.setMessageCollector(new ConsoleMessageCollector());
        //开启审计功能
        AuditManager.setAuditEnable(true);

        biConsumer.accept(MybatisFlexBootstrap.class.getName(), mybatisFlexBootstrap);
        return MybatisFlexBootstrap.class;
    }

}

